# -*- coding: UTF-8 -*-
#!/usr/bin/env python

import re
import datetime
import json
import traceback

import encodings
from pymongo.mongo_client import MongoClient
from Common import geturl

def trackprod(pid):
    if len(pid) == 0:
        pid = "1792760"
    html = geturl('http://item.jd.com/%s.html'%(pid),{})
    html = html.decode("gbk")
    html = html.encode('utf-8')
    #print html<div class="sku-name">
    rt = re.findall(r'<div id="itemInfo">[\s\S]*?<div id="name">[\s\S]*?<h1>(.*?)</h1>',html,re.S)
    if len(rt) == 0:
        rt = re.findall(r'<div class="sku-name">(.*?)</div>',html,re.S)
    print rt
    if rt:
        pstr = geturl('http://p.3.cn/prices/get?type=1&pdbp=0&skuid=J_%s'%(pid),{})
        pjson = json.loads(pstr)
        print pjson
        if pjson:
            try:
                today = datetime.date.today()
                strd = today.strftime('%Y%m%d')
                data = {'_id':pid+'-'+strd+'q','prodid':pid, 'name':rt[0],'day':strd,'price':pjson[0]['p'],'from':'jd'}
                MongoClient().contact.trackproduct.save(data)
            except Exception:
                print 'save jd prod error'
                traceback.print_exc()
            